from urllib import request, parse


# send request util
class ReqUtil(object):
    __info = False

    def __int__(self):
        return

    def __int__(self, info):
        self.__info = info
        return

    def set_info(self, info):
        self.__info = info

    # 普通请求
    def send(self, url):
        with request.urlopen(url) as f:
            data = f.read()
            if self.__info == True:
                print("Status:", f.status, f.reason)
                for k, v in f.getheaders():
                    print(k, ":", v)
            return data.decode('utf-8')

    # post请求
    def send_post(self, url, origin_url, user_agent, referer, cookie, login_data):
        # 解析数据
        if (login_data):
            login_data = parse.urlencode(login_data).encode('utf-8')
        else:
            login_data = None
        req = request.Request(url)
        req.add_header('Origin', origin_url)
        req.add_header('User-Agent', user_agent)
        req.add_header('referer', referer)
        req.add_header('Cookie', cookie)
        with request.urlopen(req, data=login_data) as f:
            # 打印请求信息
            if self.__info == True:
                print("Status:", f.status, f.reason)
                for k, v in f.getheaders():
                    print(k, ":", v)
            data = f.read()
            return data.decode('utf-8')

    # get请求
    def send_get(self, url, origin_url, user_agent, referer, cookie, login_data):
        # 解析数据
        if (login_data):
            login_data = parse.urlencode(login_data).encode('utf-8')
        else:
            login_data = None
        req = request.Request(url)
        req.add_header('User-Agent', user_agent)
        req.add_header('Origin', origin_url)
        req.add_header('Referer', referer)
        req.add_header('Cookie', cookie)
        with request.urlopen(req, data=login_data) as f:
            # 打印请求信息
            if self.__info == True:
                print("Status:", f.status, f.reason)
                for k, v in f.getheaders():
                    print(k, ":", v)
            data = f.read()
            return data.decode('utf-8')

